<template>
  <div class="params">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警示消息 -->
      <el-alert title="注意：只有三级分类才能设置参数！" type="warning" show-icon :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="params_row">
        <el-col>
          <!-- 级联选择器 -->
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children' }"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <!-- 动态参数标签页内容 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="!(this.selectedKeys.length === 3)"
            @click="showAddDialog"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" style="width: 100%" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  :key="item.attr_id"
                  v-for="item in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="deleteTag(item,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加标签输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加标签按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <!-- 作用域插槽 -->
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  @click="showRemoveParamMessageBox(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性标签项 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="!(this.selectedKeys.length === 3)"
            @click="showAddDialog"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" style="width: 100%" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  :key="item.attr_id"
                  v-for="item in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="deleteTag(item,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加标签输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加标签按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <!-- 作用域插槽 -->
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  @click="showRemoveParamMessageBox(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数/静态属性对话框 -->
    <el-dialog
      :title="'添加'+getAddName"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 对话框主体 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px">
        <el-form-item :label="getAddName" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAttr">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改动态参数/静态属性对话框 -->
    <el-dialog :title="'编辑'+getAddName" :visible.sync="editDialogVisible" width="50%">
      <!-- 对话框主体 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="120px">
        <el-form-item :label="getAddName" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择器选中数据容器
      selectedKeys: [],
      // tabs标签页活动项
      activeName: 'many',
      // 动态参数数据容器
      manyTableData: [],
      // 静态属性数据容器
      onlyTableData: [],
      // 控制添加对话框的显示和隐藏
      addDialogVisible: false,
      // 表单绑定数据
      addForm: {
        attr_name: ''
      },
      // 表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: `请输入参数/属性`, trigger: 'blur' }
        ]
      },
      // 控制编辑对话框的显示和隐藏
      editDialogVisible: false,
      // 编辑参数表单数据
      editForm: {
        attr_name: ''
      },
      // 编辑参数表单验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: `请输入参数/属性`, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      // 获取商品分类列表
      const { data: res } = await this.$http.get('categories')
      // 判断获取商品分类是否成功
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 监听级联选择器的选择
    handleChange() {
      // 获取参数数据
      this.getParamsData()
    },
    // 点击切换标签项
    handleTabsClick() {
      console.log(this.activeName)
      this.getParamsData()
    },
    // 获取参数数据
    async getParamsData() {
      if (this.selectedKeys.length !== 3) {
        // 选择分类级别错误提示
        this.$message.info('只能选择三级分类！')
        // 重置级联选择器选择内容
        this.selectedKeys = []
        // 同时也清空标签中的内容
        this.manyTableData = []
        this.onlyTableData = []
        // 级联选择器没有值则不需要请求数据
        return
      }
      // console.log(this.selectedKeys)
      // 获取动态参数数据
      const { data: res } = await this.$http.get(
        `categories/${this.getCateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      // 将每一项的attr_vals属性转换为数组
      res.data.forEach(item => {
        // item.attr_vals为空时返回空数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制添加标签输入框的显示和隐藏
        item.inputVisible = false
        // 添加标签输入框的值
        item.inputValue = ''
      })
      console.log(res.data)
      // 根据动态参数和静态属性的不同来保存数据
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 显示添加参数/属性对话框
    showAddDialog() {
      this.addDialogVisible = true
    },
    // 关闭添加参数/属性对话框时触发
    addDialogClosed() {
      // 重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 添加动态参数/静态属性
    addAttr() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.getCateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        // 提示创建参数/属性成功的消息
        this.$message.success(res.meta.msg)
        // 更新参数/属性数据
        this.getParamsData()
        // 关闭对话框
        this.addDialogVisible = false
      })
    },
    // 显示编辑参数/属性对话框
    showEditDialog(params) {
      console.log(params)
      // 保存编辑参数/属性需要的数据
      this.editForm.cat_id = params.cat_id
      this.editForm.attr_id = params.attr_id
      this.editForm.attr_sel = params.attr_sel
      // 显示编辑对话框就显示旧的参数名称
      this.editForm.attr_name = params.attr_name
      this.editDialogVisible = true
    },
    // 编辑参数/属性
    editParams() {
      // 先对编辑参数表单进行验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 进行编辑参数请求
        const { data: res } = await this.$http.put(
          `categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.editForm.attr_sel
          }
        )
        // 判断请求结果
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 显示成功提示
        this.$message.success(res.meta.msg)
        // 重新加载参数列表数据
        this.getParamsData()
        // 关闭编辑对话框
        this.editDialogVisible = false
      })
    },
    // 删除参数和属性
    async showRemoveParamMessageBox(param) {
      const removeParamResult = await this.$confirm(
        `此操作将永久删除该${this.getAddName}, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (removeParamResult !== 'confirm')
        return this.$message.info('取消删除' + this.getAddName)
      // 进行参数/属性删除
      const { data: res } = await this.$http.delete(
        `categories/${param.cat_id}/attributes/${param.attr_id}`
      )
      // 判断删除是否成功
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 显示删除成功的消息框
      this.$message.success(res.meta.msg)
      // 刷新数据
      this.getParamsData()
    },
    // 添加标签输入框，按下enter键和失去焦点都会触发
    async handleInputConfirm(param) {
      // 如果文本框中没用内容或者内容为空格
      if (param.inputValue.trim().length === 0) {
        // 重置文本框内容
        param.inputValue = ''
        // 隐藏文本框
        param.inputVisible = false
        // 文本框为空，不需要继续下面操作
        return
      }
      // 如果有内容
      // 将内容添加到获取的数据中
      param.attr_vals.push(param.inputValue)
      // 将标签的添加同步到数据库中
      const { data: res } = await this.$http.put(
        `categories/${param.cat_id}/attributes/${param.attr_id}`,
        {
          attr_name: param.attr_name,
          attr_sel: param.attr_sel,
          attr_vals: param.attr_vals.join(' ')
        }
      )
      // 判断添加标签是否成功
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 提示成功的消息
      this.$message.success(res.meta.msg)
      // 重置文本框内容
      param.inputValue = ''
      // 隐藏文本框
      param.inputVisible = false
    },
    // 控制添加标签的显示和隐藏
    showInput(param) {
      param.inputVisible = true
      // 输入框自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除参数下标签
    async deleteTag(tag,param){
      // 根据删除标签内容找到它在attr_vals数组中的索引
      const tagIndex = param.attr_vals.findIndex(item => item === tag)
      // 在数组中删除我们删除的标签
      param.attr_vals.splice(tagIndex,1)
      // 将删除参数标签的操作同步到数据库
      const { data: res } = await this.$http.put(
        `categories/${param.cat_id}/attributes/${param.attr_id}`,
        {
          attr_name: param.attr_name,
          attr_sel: param.attr_sel,
          attr_vals: param.attr_vals.join(' ')
        }
      )
      if(res.meta.status !== 200) return this.$message.error(res.mata.msg)
      // 提示标签数据更新成功
      this.$message.success(res.meta.msg)
    }
  },
  computed: {
    // 获取级联选择器选中三级分类的最后一项的id
    getCateId() {
      if (this.selectedKeys.length !== 3) {
        return null
      }
      return this.selectedKeys[2]
    },
    // 根据当前标签页判断添加对话框添加什么
    getAddName() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.params_row {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>